package com.situ.science.aspect;

import com.situ.science.controller.LogController;
import com.situ.science.mapper.LogMapper;
import com.situ.science.pojo.Admin;
import com.situ.science.pojo.Logs;
import com.situ.science.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.Timestamp;
import java.util.Map;

@Log4j2
@Aspect
@Component
public class LogAspect {
    @Autowired
     private LogMapper logMapper;
    /**
     * 日志级别-INFO
     */
    String LOG_INFO = "INFO";

    /**
     * 日志级别-DEBUG
     */
    String LOG_DEBUG = "DEBUG";

    /**
     * 日志级别-ERROR
     */
    String LOG_ERROR = "ERROR";

    //ThreadLocal是线程隔离的
    private ThreadLocal<Logs> threadLocal = new ThreadLocal<>();

    /**
     * 日志切点
     */
    @Pointcut("@annotation(com.situ.science.annotation.MyLog)")
    public void logPointcut() {}

    @AfterReturning(value = "logPointcut()")
    public void after(JoinPoint joinPoint) {
        Logs logs = new Logs();
        logs.setAction(joinPoint.getSignature().getName());//获取方法名称
        logs.setTimestamp(new Timestamp(System.currentTimeMillis()));

        //获取当前用户信息
        //String username = map.get("name").toString();
        //从token中获取当前用户的用户名
        Integer id = getCurrentUsernameFromToken();
        logs.setUserId(id);
        threadLocal.set(logs);
        log.info("Executing method: {}", logs.getAction());
        System.out.println(logs);
        logMapper.add(logs);
    }

    private Integer getCurrentUsernameFromToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");

        // 检查 token 是否为空
        if (token == null || token.isEmpty()) {
            // 未登录时返回 null 或者一个默认的 id
            return -1;  // 或者返回一个特殊的用户 ID 代表未登录用户
        }

        // 解析 token
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("id");
        return id;
    }
}
